package com.xinhe.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.app.AppService;
import com.wechat.pay.java.service.payments.app.model.Amount;
import com.wechat.pay.java.service.payments.app.model.PrepayRequest;
import com.wechat.pay.java.service.payments.app.model.PrepayResponse;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.xinhe.web.common.Result;
import com.xinhe.web.reposity.WeixinConfigRepository;
import com.xinhe.web.selfpay.WeixinJsapiService;
import com.xinhe.web.selfpay.WeixinNativeService;
import com.xinhe.web.service.WeixinTradeService;
import com.xinhe.web.session.UserSessionManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Api(value = "test区域", tags = {"test区域"})
@RestController
@RequestMapping(value = {"/test"}, produces = {"application/json;charset=UTF-8"})
public class Test {

    //前提是请求头要传x-access-token
    @Autowired
    UserSessionManager userSessionManager;
    @Autowired
    WeixinTradeService weixinTradeService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    WeixinConfigRepository weixinConfigRepository;
    @Autowired
    WeixinJsapiService weixinJsapiService;
    @Autowired
    WeixinNativeService weixinNativeService;


    /** 商户号 */
    public static String merchantId = "1616713201";
    /** 商户API私钥路径,这里写的是本地路径，线上的话要换成docker容器内的证书路径（volumns映射）*/
    //public static String privateKeyPath = "/zhanghou/apiclient_key.pem";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "57906AE4C493222D0DDD03D81A3A2F2AA93B8D19";
    /** 商户APIV3密钥 */
    public static String apiV3Key = "12345678901234567890ABCDEFGHIJKL";

    public static AppService service;
    @Autowired
    private ResourceLoader resourceLoader;

    @ApiOperation(httpMethod = "GET", value = "测试获取用户id")
    @RequestMapping({"/test"})
    public Result test() {
        Long userId = this.userSessionManager.getUserId();
        System.out.println("测试获取用户id:"+userId);
        return Result.ok(userId);
    }
    @ApiOperation(value = "接收腾讯云回调建群接口1", hidden = true)
    @PostMapping(path = "/acceptWeixin")
    public void acceptTecent1(@RequestBody JSONObject jsonObject) {
        log.info("回调入口。。。。。。。。。" + JSONObject.toJSONString(jsonObject));
    }

    @ApiOperation(httpMethod = "GET", value = "测试支付")
    @RequestMapping({"/testpay"})
    public void testpay() throws Exception{
        /*我的信息
        userid：604183377410523136
        openid：olYZb5aMoVTziZtD8MYK5dIV8TmE
        unionid：oaniQ6U5MUVuwINMyxdA-K4f8yWg
        configid：519802482830868480
        appid：wx2425d0af98810b00
        appsecret：f74746117f13a69ef272055921e81b3f
        mchid:1616713201
        paykey:af42f8b7ecc71d8995b8f98bd6baad28
        */
        String privateKeyPath = null;
        //todo 注意本地运行的话可以使用这种绝对路径的方式，线上的话使用相对路径，记得改成docker容器内部的证书路径
        //本地运行，打开
        /*Resource resource = resourceLoader.getResource("classpath:cert/apiclient_key.pem");
        try {
            privateKeyPath = resource.getFile().getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //线上运行，打开
        privateKeyPath="/zhanghou/apiclient_key.pem";
        // 初始化商户配置
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();

        // 初始化服务
        service = new AppService.Builder().config(config).build();
        // ... 调用接口
        prepay();
    }
    /** APP支付下单 */
    public void prepay() {
        PrepayRequest request = new PrepayRequest();
        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
        Amount amount = new Amount();
        amount.setTotal(1);
        amount.setCurrency("CNY");
        request.setAmount(amount);
        request.setAppid("wx2425d0af98810b00");
        request.setMchid("1616713201");
        request.setDescription("测试商品999");
        request.setNotifyUrl("http://1941w5190a.yicp.fun:49760/test/acceptWeixin");
        request.setOutTradeNo("out_trade_no_000");
        Payer payer = new Payer();
        payer.setOpenid("olYZb5aMoVTziZtD8MYK5dIV8TmE");
        // 调用接口
        PrepayResponse prepay = service.prepay(request);
        System.out.println("哈哈哈："+ JSONObject.toJSONString(prepay));
    }

    @ApiOperation(httpMethod = "GET", value = "测试jsapi支付")
    @RequestMapping({"/testjsapipay"})
    public Result testjsapipay() throws Exception{
        return weixinJsapiService.jsapiPay(null);
    }
    @ApiOperation(httpMethod = "GET", value = "测试native扫码支付")
    @RequestMapping({"/testnativepay"})
    public Result testnativepay() throws Exception{
        return weixinNativeService.testnativepay();
    }
    @ApiOperation(value = "接收微信native扫码支付回调", hidden = true)
    @RequestMapping(path = "/nativeCallback",method = RequestMethod.POST)
    public ResponseEntity.BodyBuilder nativeCallback(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进来了。。。。。。");
        return weixinNativeService.payCallback(request,response);
    }

    @ApiOperation(httpMethod = "GET", value = "测试native退款")
    @RequestMapping({"/testnativepayrefund"})
    public Result testnativepayrefund(){
         return weixinNativeService.testnativepayrefund();
    }

    @ApiOperation(value = "接收微信native退款回调", hidden = true)
    @RequestMapping(path = "/refundCallback",method = RequestMethod.POST)
    public ResponseEntity.BodyBuilder refundCallback(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("退款回调进来了。。。。。。");
        return weixinNativeService.refundCallback(request,response);
    }





}
